package com.sddnytsh.body_buildingsystem.components

import android.R
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ScrollableTabRow
import androidx.compose.material.Tab
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SegmentedButtonDefaults.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.sddnytsh.body_buildingsystem.topic.Exercise
import com.sddnytsh.body_buildingsystem.topic.RunData
import java.time.LocalDate
import java.util.Timer
import java.util.TimerTask

//@Composable
//fun Page3() {
//    val workoutData = remember {
//        generateWorkoutData()
//    }
//
//    LazyColumn(
//        modifier = Modifier
//            .fillMaxSize()
//            .padding(16.dp),
//        verticalArrangement = Arrangement.spacedBy(16.dp)
//    ) {
//        item {
//            WeeklySummary(workoutData)
//        }
//        item {
//            CaloriesChart(workoutData)
//        }
//        item {
//            WorkoutDataTable(workoutData)
//        }
//    }
//}
//
//fun generateWorkoutData(): List<RunData> {
//    return listOf(
//        RunData(
//            date = LocalDate.of(2024, 1, 15),
//            calories = 450,
//            steps = 8560,
//            duration = 45,
//            distance = 4.2
//        ),
//        RunData(
//            date = LocalDate.of(2024, 1, 16),
//            calories = 280,
//            steps = 7230,
//            duration = 38,
//            distance = 3.5
//        ),
//        RunData(
//            date = LocalDate.of(2024, 1, 17),
//            calories = 450,
//            steps = 12450,
//            duration = 65,
//            distance = 6.8
//        ),
//        RunData(
//            date = LocalDate.of(2024, 1, 18),
//            calories = 190,
//            steps = 5120,
//            duration = 25,
//            distance = 2.1
//        ),
//        RunData(
//            date = LocalDate.of(2024, 1, 19),
//            calories = 380,
//            steps = 9430,
//            duration = 52,
//            distance = 5.3
//        ),
//        RunData(
//            date = LocalDate.of(2024, 1, 20),
//            calories = 510,
//            steps = 13890,
//            duration = 72,
//            distance = 7.5
//        ),
//        RunData(
//            date = LocalDate.of(2024, 1, 21),
//            calories = 290,
//            steps = 6780,
//            duration = 40,
//            distance = 3.8
//        )
//    )
//}

@Composable
fun Page3() {
    var expanded by remember { mutableStateOf(false) }
    var selectedExercise by remember { mutableStateOf<Exercise?>(null) }
    var isExercising by remember { mutableStateOf(false) }
    var elapsedTime by remember { mutableStateOf(0L) }
    var timer: Timer? by remember { mutableStateOf(null) }

    // 速度输入（仅当运动支持速度时显示）
    var speed by remember { mutableStateOf("") }

    // 心率输入（仅当运动支持心率时显示）
    var heartRate by remember { mutableStateOf("") }

    val exercises = listOf<Exercise>(
        Exercise(
            1,
            "跑步",
            "有氧运动",
            "户外或室内跑步，提高心肺功能",
            true,
            true,
            "30/8/2025 09:08:27",
            "30/8/2025 09:08:27"
        ),
        Exercise(
            2,
            "步行",
            "有氧运动",
            "快走或慢走，适合初学者",
            true,
            true,
            "30/8/2025 09:08:27",
            "30/8/2025 09:08:27"
        ),
        // 其他运动数据...






        Exercise(
            20,
            "普拉提",
            "核心训练",
            "提高核心力量和身体控制",
            false,
            false,
            "30/8/2025 09:08:27",
            "30/8/2025 09:08:27"
        )
    )

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // 运动选择下拉菜单
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentSize(Alignment.TopStart)
        ) {
            OutlinedButton(
                onClick = { if (!isExercising) expanded = true },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp),
                enabled = !isExercising,
                colors = ButtonDefaults.outlinedButtonColors()
            ) {
                Text(
                    selectedExercise?.name ?: "选择运动",
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Start
                )
                Icon(
                    imageVector = if (expanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown,
                    contentDescription = "下拉菜单"
                )
            }

            DropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false },
                modifier = Modifier.fillMaxWidth(0.9f)
            ) {
                exercises.forEach { exercise ->
                    DropdownMenuItem(
                        text = {
                            Column {
                                Text(text = exercise.name)
                            }
                        },
                        onClick = {
                            selectedExercise = exercise
                            expanded = false
                        }
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 显示运动详情
        selectedExercise?.let { exercise ->
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(text = exercise.description)
                    Spacer(modifier = Modifier.height(8.dp))
                    Row {
                        if (exercise.hasSpeed) {
                            Icon(
                                imageVector = Icons.Default.Face,
                                contentDescription = "速度监测",
                                modifier = Modifier.size(20.dp)
                            )
                            Spacer(modifier = Modifier.width(4.dp))
                            Text("速度监测")
                            Spacer(modifier = Modifier.width(16.dp))
                        }
                        if (exercise.hasHeartRate) {
                            Icon(
                                imageVector = Icons.Default.Favorite,
                                contentDescription = "心率监测",
                                modifier = Modifier.size(20.dp)
                            )
                            Spacer(modifier = Modifier.width(4.dp))
                            Text("心率监测")
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 计时器显示
            Text(
                text = "已运动: ${formatTime(elapsedTime)}",
                style = MaterialTheme.typography.h4,
                modifier = Modifier.align(Alignment.CenterHorizontally)
            )

            Spacer(modifier = Modifier.height(16.dp))

            // 数据输入字段（根据运动类型显示）
            if (exercise.hasSpeed && !isExercising) {
                OutlinedTextField(
                    value = speed,
                    onValueChange = { speed = it },
                    label = { Text("平均速度 (km/h)") },
                    modifier = Modifier.fillMaxWidth(),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                    //
                )
                Spacer(modifier = Modifier.height(8.dp))
            }

            if (exercise.hasHeartRate && !isExercising) {
                OutlinedTextField(
                    value = heartRate,
                    onValueChange = { heartRate = it },
                    label = { Text("平均心率 (bpm)") },
                    modifier = Modifier.fillMaxWidth(),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                    //
                )
                Spacer(modifier = Modifier.height(8.dp))
            }

            // 开始/结束按钮
            Button(
                onClick = {
                    if (isExercising) {
                        // 停止运动
                        timer?.cancel()
                        isExercising = false
                        // 这里可以添加上传数据的逻辑
                    } else {
                        // 开始运动
                        isExercising = true
                        elapsedTime = 0L
                        timer = Timer().apply {
                            scheduleAtFixedRate(object : TimerTask() {
                                override fun run() {
                                    elapsedTime += 1000
                                }
                            }, 0, 1000)
                        }
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = if (isExercising) Color.Red else Color.White,
                )
            ) {
                Text(if (isExercising) "结束运动" else "开始运动")
            }
        }
    }
}

// 格式化时间显示
fun formatTime(millis: Long): String {
    val seconds = (millis / 1000) % 60
    val minutes = (millis / (1000 * 60)) % 60
    val hours = (millis / (1000 * 60 * 60))

    return if (hours > 0) {
        String.format("%02d:%02d:%02d", hours, minutes, seconds)
    } else {
        String.format("%02d:%02d", minutes, seconds)
    }
}